"use strict";
const path = require('path')
const xtpl = require('xtpl')
const mongodbDatas = require(path.join(__dirname, '../tools/Mongodb-datas.js'))
function pathHtml(name) {
    return path.join(__dirname, '../views/' + name + '.html')
}
exports.getStudentPage = (req, res) => {
    const search = req.query.search || ''
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    mongodbDatas.findMany('studentinfo', {name: {$regex: search}}, (doc) => {
        xtpl.renderFile(pathHtml('studentlist'), {
            loginedname: 'mini',
            studentList: doc,
            search: search
        }, (err, data) => {
            res.cookie('name', 'tobi', {path: '/', secure: true});
            console.log('ok accout');
            res.end(data)
        })
    })
}

exports.getaddStudentPage = (req, res) => {
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    xtpl.renderFile(pathHtml('add'), {}, (err, data) => {
        res.cookie('name', 'tobi', {path: '/', secure: true});
        console.log('ok add');
        res.end(data)
    })
}
exports.setaddStudentPage = (req, res) => {
    const params = req.body
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    mongodbDatas.insertOne('studentinfo', params, (result) => {
        if (result) {
            res.end('<script>window.location.href = "/studentmanager/list"</script>')
        } else {
            res.end('<script>alert("新增失败");window.location.href = "/studentmanager/list"</script>')
        }
    })
}
exports.deleteStudentPage = (req, res) => {
    const id = req.query._id
    const result = {status: 1, message: "删除成功"}
    mongodbDatas.deleteOne('studentinfo', {_id: mongodbDatas.ObjectId(id)}, (doc) => {
        console.log(doc);
        if (!doc) {
            result.status = 0
            result.message = "删除失败"
        }
        res.end(JSON.stringify(result))
    })
}
exports.geteditStudentPage = (req, res) => {
    const id = req.params._id
    mongodbDatas.findOne('studentinfo', {_id: mongodbDatas.ObjectId(id)}, (doc) => {
        xtpl.renderFile(path.join(__dirname, '../views/edit.html'), {student: doc}, (err, data) => {
            res.setHeader('Content-Type', 'text/html; charset=utf-8')
            res.end(data)
        })
    })
}
exports.seteditStudentPage = (req, res) => {
    const params = req.body
    const id = req.params._id
    mongodbDatas.uptateOne('studentinfo', {_id: mongodbDatas.ObjectId(id)}, params, (isEdit) => {
        if (isEdit) {
            res.end('<script>window.location.href = "/studentmanager/list"</script>')
        } else {
            res.end('<script>alert("更新失败");window.location.href = "/studentmanager/list"</script>')
        }
    })
}